from operator import itemgetter
from django.db import models
from monulu.raid.models import Instance, Character, Raid, RaidLoot

class SKList(models.Model):
    name = models.CharField(max_length=200)
    class Meta:
        ordering = ['name',]
    def __unicode__(self):
        return self.name 
    def getInstances(self):
        return self.skinstance_set.all()
    def getInitialRanks(self):
        return self.skstart_set.all().order_by('initial_rank')
    def getSuicides(self):
        return self.sksuicide_set.all().order_by('raid', 'skorder')
    def getRaids(self):
        return Raid.objects.filter(instance__in=self.getInstances()).order_by('start_time')
    def getLastRaid(self):
        return Raid.objects.filter(instance__in=self.getInstances()).order_by('-start_time')[0]
    def getRanks(self, to_raid='0'):
        ranks = {}            # character.pk : rank    | id and rank of everyone ever
       
        class _crank(object):
            def __init__(self, pk, rank):
                self.pk = pk
                self.rank = rank
            def __cmp__(self, other):
                return cmp(self.rank, other.rank)
               
        for i in self.getInitialRanks():
            ranks[i.character.pk] = i.initial_rank
            
        raids = self.getRaids()
        
        for raid in raids:
            if to_raid and raid.pk > to_raid:
                break
            raiders = [_crank(r.character.pk,ranks[r.character.pk]) for r in raid.raiders()]
            raiders.sort()
            for s in SKSuicide.objects.filter(raid=raid).order_by('skorder'):
                swaprank = 0
                maxrank = raiders[len(raiders)-1].rank
                for raider in raiders:
                    if raider.pk == s.character.pk:
                        swaprank = raider.rank
                        raider.rank = maxrank
                    elif swaprank:
                        raider.rank, swaprank = swaprank, raider.rank
                raiders.sort()
            for raider in raiders:
                ranks[raider.pk] = raider.rank
        return sorted(ranks.iteritems(), key=itemgetter(1))
    
class SKInstance(models.Model):
    """Ties a list to instance(s)"""
    sklist = models.ForeignKey(SKList)
    instance = models.ForeignKey(Instance)
    def __unicode__(self):
        return self.instance.name
    
class SKStart(models.Model): 
    sklist = models.ForeignKey(SKList)
    character = models.ForeignKey(Character)
    initial_rank = models.IntegerField()
    def __unicode__(self):
        return self.character.name

class SKSuicide(RaidLoot):
    sklist = models.ForeignKey(SKList)
    is_suicide = models.BooleanField()
    skorder = models.IntegerField()
    
    